import { MigrationInterface, QueryRunner, Table, TableForeignKey } from 'typeorm';

export class CreateWorkspaceInvitationTable1709711234567 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        name: 'workspace_invitations',
        columns: [
          {
            name: 'id',
            type: 'uuid',
            isPrimary: true,
            isGenerated: true,
            generationStrategy: 'uuid',
          },
          {
            name: 'workspace_id',
            type: 'uuid',
          },
          {
            name: 'email',
            type: 'varchar',
          },
          {
            name: 'role',
            type: 'enum',
            enum: ['owner', 'admin', 'member', 'guest'],
          },
          {
            name: 'token',
            type: 'varchar',
            length: '64',
            isUnique: true,
          },
          {
            name: 'expires_at',
            type: 'timestamp',
          },
          {
            name: 'is_accepted',
            type: 'boolean',
            default: false,
          },
          {
            name: 'created_at',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
          },
          {
            name: 'updated_at',
            type: 'timestamp',
            default: 'CURRENT_TIMESTAMP',
            onUpdate: 'CURRENT_TIMESTAMP',
          },
        ],
      }),
      true
    );

    // 添加外键约束
    await queryRunner.createForeignKey(
      'workspace_invitations',
      new TableForeignKey({
        columnNames: ['workspace_id'],
        referencedColumnNames: ['id'],
        referencedTableName: 'workspaces',
        onDelete: 'CASCADE',
      })
    );

    // 添加索引
    await queryRunner.query(
      'CREATE INDEX "IDX_workspace_invitations_token" ON "workspace_invitations" ("token")'
    );
    await queryRunner.query(
      'CREATE INDEX "IDX_workspace_invitations_email" ON "workspace_invitations" ("email")'
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 删除索引
    await queryRunner.query('DROP INDEX "IDX_workspace_invitations_email"');
    await queryRunner.query('DROP INDEX "IDX_workspace_invitations_token"');
    
    // 删除表（会自动删除外键约束）
    await queryRunner.dropTable('workspace_invitations');
  }
} 